package main

import (
	"archive/tar"
	"compress/gzip"
	"crypto/sha256"
	"database/sql"
	"encoding/hex"
	"encoding/json"
	"flag"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"sort"
	"strings"
	"sync"
	"time"

	_ "github.com/mattn/go-sqlite3"
	"golang.org/x/mod/semver"
)

// 包元数据结构
type PackageMetadata struct {
	Name         string            `json:"name"`
	Version      string            `json:"version"`
	Description  string            `json:"description"`
	Author       string            `json:"author"`
	License      string            `json:"license"`
	Homepage     string            `json:"homepage"`
	DownloadURL  string            `json:"download_url"`
	Checksum     string            `json:"checksum"`
	Dependencies map[string]string `json:"dependencies"`
	Files        []string          `json:"files"`
}

// 依赖解析结果
type ResolvedDependency struct {
	Name    string
	Version string
	Path    string
}

// 包管理器
type PackageManager struct {
	config        Config
	cacheDir      string
	installDir    string
	db            *sql.DB
	httpClient    *http.Client
	mutex         sync.Mutex
	resolvedDeps  map[string]ResolvedDependency
	availablePkgs map[string][]string // 包名 -> 可用版本列表
	metadataCache map[string]PackageMetadata
}

// 配置结构
type Config struct {
	IndexURL      string `json:"index_url"`
	CacheDir      string `json:"cache_dir"`
	InstallDir    string `json:"install_dir"`
	Concurrency   int    `json:"concurrency"`
	Timeout       int    `json:"timeout"`
	VerifySSL     bool   `json:"verify_ssl"`
	Verbose       bool   `json:"verbose"`
	Debug         bool   `json:"debug"`
	DefaultBranch string `json:"default_branch"`
}

// 初始化包管理器
func NewPackageManager(configPath string) (*PackageManager, error) {
	// 加载配置
	config, err := loadConfig(configPath)
	if err != nil {
		return nil, fmt.Errorf("加载配置失败: %v", err)
	}

	// 创建必要的目录
	for _, dir := range []string{config.CacheDir, config.InstallDir} {
		if _, err := os.Stat(dir); os.IsNotExist(err) {
			if err := os.MkdirAll(dir, 0755); err != nil {
				return nil, fmt.Errorf("创建目录失败: %v", err)
			}
		}
	}

	// 打开数据库
	dbPath := filepath.Join(config.CacheDir, "packages.db")
	db, err := sql.Open("sqlite3", dbPath)
	if err != nil {
		return nil, fmt.Errorf("打开数据库失败: %v", err)
	}

	// 初始化表结构
	if err := initDB(db); err != nil {
		return nil, fmt.Errorf("初始化数据库失败: %v", err)
	}

	// 创建 HTTP 客户端
	httpClient := &http.Client{
		Timeout: time.Duration(config.Timeout) * time.Second,
	}

	return &PackageManager{
		config:        config,
		cacheDir:      config.CacheDir,
		installDir:    config.InstallDir,
		db:            db,
		httpClient:    httpClient,
		resolvedDeps:  make(map[string]ResolvedDependency),
		availablePkgs: make(map[string][]string),
		metadataCache: make(map[string]PackageMetadata),
	}, nil
}

// 加载配置文件
func loadConfig(path string) (Config, error) {
	// 默认配置
	config := Config{
		IndexURL:      "https://pypi.org/pypi",
		CacheDir:      filepath.Join(os.UserHomeDir(), ".gomod", "cache"),
		InstallDir:    filepath.Join(os.UserHomeDir(), ".gomod", "packages"),
		Concurrency:   5,
		Timeout:       30,
		VerifySSL:     true,
		Verbose:       false,
		Debug:         false,
		DefaultBranch: "master",
	}

	// 如果配置文件存在，则加载
	if _, err := os.Stat(path); !os.IsNotExist(err) {
		data, err := ioutil.ReadFile(path)
		if err != nil {
			return config, fmt.Errorf("读取配置文件失败: %v", err)
		}

		if err := json.Unmarshal(data, &config); err != nil {
			return config, fmt.Errorf("解析配置文件失败: %v", err)
		}
	}

	return config, nil
}

// 初始化数据库
func initDB(db *sql.DB) error {
	// 创建包信息表
	_, err := db.Exec(`
		CREATE TABLE IF NOT EXISTS packages (
			name TEXT PRIMARY KEY,
			versions JSON NOT NULL,
			updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
		)
	`)
	if err != nil {
		return err
	}

	// 创建已安装包表
	_, err = db.Exec(`
		CREATE TABLE IF NOT EXISTS installed_packages (
			name TEXT,
			version TEXT,
			path TEXT,
			installed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
			PRIMARY KEY (name, version)
		)
	`)
	if err != nil {
		return err
	}

	return nil
}

// 获取包的可用版本
func (pm *PackageManager) GetAvailableVersions(packageName string) ([]string, error) {
	// 先检查缓存
	if versions, ok := pm.availablePkgs[packageName]; ok {
		return versions, nil
	}

	// 检查数据库
	var versionsJSON string
	err := pm.db.QueryRow(`
		SELECT versions FROM packages WHERE name = ?
	`, packageName).Scan(&versionsJSON)

	if err == nil {
		var versions []string
		if err := json.Unmarshal([]byte(versionsJSON), &versions); err != nil {
			return nil, fmt.Errorf("解析版本信息失败: %v", err)
		}
		pm.availablePkgs[packageName] = versions
		return versions, nil
	}

	if err != sql.ErrNoRows {
		return nil, fmt.Errorf("查询数据库失败: %v", err)
	}

	// 从远程索引获取
	versions, err := pm.fetchVersionsFromRemote(packageName)
	if err != nil {
		return nil, fmt.Errorf("从远程获取版本失败: %v", err)
	}

	// 保存到数据库
	versionsJSON, err = json.Marshal(versions)
	if err != nil {
		return nil, fmt.Errorf("序列化版本信息失败: %v", err)
	}

	_, err = pm.db.Exec(`insert or replace into packages (name, versions) values (?, ?)`, packageName, versionsJSON)
	if err != nil {
		return nil, fmt.Errorf("保存版本信息失败: %v", err)
	}

	pm.availablePkgs[packageName] = versions
	return versions, nil
}

// 从远程索引获取版本
func (pm *PackageManager) fetchVersionsFromRemote(packageName string) ([]string, error) {
	// 实际实现中会调用索引 API
	// 这里简化为模拟获取
	versions := []string{
		"v1.0.0", "v1.0.1", "v1.1.0", "v1.2.0",
		"v2.0.0", "v2.1.0", "v2.1.1", "v2.2.0",
	}

	// 排序版本
	sort.Slice(versions, func(i, j int) bool {
		return semver.Compare(versions[i], versions[j]) < 0
	})

	return versions, nil
}

// 获取包元数据
func (pm *PackageManager) GetPackageMetadata(packageName, version string) (PackageMetadata, error) {
	// 检查缓存
	cacheKey := fmt.Sprintf("%s@%s", packageName, version)
	if metadata, ok := pm.metadataCache[cacheKey]; ok {
		return metadata, nil
	}

	// 从远程获取
	metadata, err := pm.fetchMetadataFromRemote(packageName, version)
	if err != nil {
		return PackageMetadata{}, fmt.Errorf("获取元数据失败: %v", err)
	}

	pm.metadataCache[cacheKey] = metadata
	return metadata, nil
}

// 从远程获取元数据
func (pm *PackageManager) fetchMetadataFromRemote(packageName, version string) (PackageMetadata, error) {
	// 实际实现中会调用索引 API
	// 这里简化为模拟获取
	metadata := PackageMetadata{
		Name:        packageName,
		Version:     version,
		Description: "示例包描述",
		Author:      "示例作者",
		License:     "MIT",
		Homepage:    "https://example.com",
		DownloadURL: fmt.Sprintf("https://example.com/packages/%s-%s.tar.gz", packageName, version),
		Checksum:    "sha256:1234567890abcdef1234567890abcdef1234567890abcdef1234567890",
		Dependencies: map[string]string{
			"dependency1": ">=1.0.0",
			"dependency2": "^2.0.0",
		},
		Files: []string{"README.md", "LICENSE", "src/main.go"},
	}

	return metadata, nil
}

// 解析依赖
func (pm *PackageManager) ResolveDependencies(packageName, versionConstraint string) ([]ResolvedDependency, error) {
	// 清理版本约束（移除前缀 v）
	if strings.HasPrefix(versionConstraint, "v") {
		versionConstraint = versionConstraint[1:]
	}

	// 获取可用版本
	versions, err := pm.GetAvailableVersions(packageName)
	if err != nil {
		return nil, fmt.Errorf("获取可用版本失败: %v", err)
	}

	// 查找匹配的最高版本
	var resolvedVersion string
	for i := len(versions) - 1; i >= 0; i-- {
		version := versions[i]
		// 移除前缀 v
		if strings.HasPrefix(version, "v") {
			version = version[1:]
		}
		if semver.Compare(version, versionConstraint) >= 0 {
			resolvedVersion = versions[i]
			break
		}
	}

	if resolvedVersion == "" {
		return nil, fmt.Errorf("找不到符合约束 %s 的版本", versionConstraint)
	}

	// 递归解析依赖
	resolvedDeps := make(map[string]ResolvedDependency)
	if err := pm.resolveDependenciesRecursive(packageName, resolvedVersion, resolvedDeps); err != nil {
		return nil, err
	}

	// 转换为切片
	result := make([]ResolvedDependency, 0, len(resolvedDeps))
	for _, dep := range resolvedDeps {
		result = append(result, dep)
	}

	return result, nil
}

// 递归解析依赖
func (pm *PackageManager) resolveDependenciesRecursive(packageName, version string, resolvedDeps map[string]ResolvedDependency) error {
	// 检查是否已解析
	key := fmt.Sprintf("%s@%s", packageName, version)
	if _, ok := resolvedDeps[key]; ok {
		return nil
	}

	// 获取元数据
	metadata, err := pm.GetPackageMetadata(packageName, version)
	if err != nil {
		return err
	}

	// 创建已解析依赖项
	dep := ResolvedDependency{
		Name:    packageName,
		Version: version,
		Path:    filepath.Join(pm.installDir, packageName, version),
	}

	// 记录已解析依赖
	resolvedDeps[key] = dep

	// 解析子依赖
	for depName, constraint := range metadata.Dependencies {
		// 清理版本约束
		if strings.HasPrefix(constraint, "v") {
			constraint = constraint[1:]
		}

		// 获取可用版本
		versions, err := pm.GetAvailableVersions(depName)
		if err != nil {
			return fmt.Errorf("获取依赖 %s 的可用版本失败: %v", depName, err)
		}

		// 查找匹配的最高版本
		var resolvedDepVersion string
		for i := len(versions) - 1; i >= 0; i-- {
			depVersion := versions[i]
			// 移除前缀 v
			if strings.HasPrefix(depVersion, "v") {
				depVersion = depVersion[1:]
			}
			if semver.Compare(depVersion, constraint) >= 0 {
				resolvedDepVersion = versions[i]
				break
			}
		}

		if resolvedDepVersion == "" {
			return fmt.Errorf("找不到符合约束 %s 的依赖 %s 版本", constraint, depName)
		}

		// 递归解析子依赖
		if err := pm.resolveDependenciesRecursive(depName, resolvedDepVersion, resolvedDeps); err != nil {
			return err
		}
	}

	return nil
}

// 下载包
func (pm *PackageManager) DownloadPackage(metadata PackageMetadata) (string, error) {
	// 创建缓存路径
	cachePath := filepath.Join(pm.cacheDir, "packages",
		fmt.Sprintf("%s-%s.tar.gz", metadata.Name, metadata.Version))

	// 检查缓存
	if _, err := os.Stat(cachePath); err == nil {
		// 验证校验和
		if pm.config.VerifySSL {
			checksum, err := calculateChecksum(cachePath)
			if err != nil {
				return "", fmt.Errorf("计算缓存文件校验和失败: %v", err)
			}

			if checksum != metadata.Checksum {
				fmt.Println("缓存文件校验和不匹配，重新下载")
				os.Remove(cachePath)
			} else {
				fmt.Printf("使用缓存的 %s@%s\n", metadata.Name, metadata.Version)
				return cachePath, nil
			}
		}
	}

	// 创建缓存目录
	cacheDir := filepath.Dir(cachePath)
	if _, err := os.Stat(cacheDir); os.IsNotExist(err) {
		if err := os.MkdirAll(cacheDir, 0755); err != nil {
			return "", fmt.Errorf("创建缓存目录失败: %v", err)
		}
	}

	// 下载文件
	fmt.Printf("正在下载 %s@%s...\n", metadata.Name, metadata.Version)
	resp, err := pm.httpClient.Get(metadata.DownloadURL)
	if err != nil {
		return "", fmt.Errorf("下载失败: %v", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return "", fmt.Errorf("下载失败: HTTP %d", resp.StatusCode)
	}

	// 创建临时文件
	tmpFile, err := os.CreateTemp(cacheDir, fmt.Sprintf("%s-*.tmp", metadata.Name))
	if err != nil {
		return "", fmt.Errorf("创建临时文件失败: %v", err)
	}
	tmpFilePath := tmpFile.Name()
	defer os.Remove(tmpFilePath) // 清理临时文件
	defer tmpFile.Close()

	// 写入下载内容
	if _, err := io.Copy(tmpFile, resp.Body); err != nil {
		return "", fmt.Errorf("写入文件失败: %v", err)
	}

	// 验证校验和
	if pm.config.VerifySSL {
		checksum, err := calculateChecksum(tmpFilePath)
		if err != nil {
			return "", fmt.Errorf("计算校验和失败: %v", err)
		}

		if checksum != metadata.Checksum {
			return "", fmt.Errorf("校验和不匹配，下载可能损坏")
		}
	}

	// 重命名为正式缓存文件
	if err := os.Rename(tmpFilePath, cachePath); err != nil {
		return "", fmt.Errorf("重命名文件失败: %v", err)
	}

	return cachePath, nil
}

// 计算文件校验和
func calculateChecksum(filePath string) (string, error) {
	file, err := os.Open(filePath)
	if err != nil {
		return "", err
	}
	defer file.Close()

	hash := sha256.New()
	if _, err := io.Copy(hash, file); err != nil {
		return "", err
	}

	return fmt.Sprintf("sha256:%s", hex.EncodeToString(hash.Sum(nil))), nil
}

// 安装包
func (pm *PackageManager) InstallPackage(packageName, version string) error {
	// 检查是否已安装
	if pm.IsPackageInstalled(packageName, version) {
		fmt.Printf("%s@%s 已安装\n", packageName, version)
		return nil
	}

	// 解析依赖
	dependencies, err := pm.ResolveDependencies(packageName, version)
	if err != nil {
		return fmt.Errorf("解析依赖失败: %v", err)
	}

	// 打印依赖树
	fmt.Println("依赖树:")
	for _, dep := range dependencies {
		fmt.Printf("- %s@%s\n", dep.Name, dep.Version)
	}

	// 创建并发控制
	semaphore := make(chan struct{}, pm.config.Concurrency)
	var wg sync.WaitGroup
	errs := make(chan error, len(dependencies))

	// 安装所有依赖
	for _, dep := range dependencies {
		wg.Add(1)
		semaphore <- struct{}{} // 获取令牌

		go func(d ResolvedDependency) {
			defer wg.Done()
			defer func() { <-semaphore }() // 释放令牌

			metadata, err := pm.GetPackageMetadata(d.Name, d.Version)
			if err != nil {
				errs <- fmt.Errorf("获取 %s@%s 元数据失败: %v", d.Name, d.Version, err)
				return
			}

			// 下载包
			packagePath, err := pm.DownloadPackage(metadata)
			if err != nil {
				errs <- fmt.Errorf("下载 %s@%s 失败: %v", d.Name, d.Version, err)
				return
			}

			// 安装包
			if err := pm.installPackageFromFile(packagePath, metadata); err != nil {
				errs <- fmt.Errorf("安装 %s@%s 失败: %v", d.Name, d.Version, err)
				return
			}

			fmt.Printf("成功安装 %s@%s\n", d.Name, d.Version)
		}(dep)
	}

	// 等待所有 goroutine 完成
	wg.Wait()
	close(errs)

	// 检查是否有错误
	for err := range errs {
		if err != nil {
			return err
		}
	}

	return nil
}

// 从文件安装包
func (pm *PackageManager) installPackageFromFile(packagePath string, metadata PackageMetadata) error {
	// 创建安装目录
	installPath := filepath.Join(pm.installDir, metadata.Name, metadata.Version)
	if _, err := os.Stat(installPath); os.IsNotExist(err) {
		if err := os.MkdirAll(installPath, 0755); err != nil {
			return fmt.Errorf("创建安装目录失败: %v", err)
		}
	}

	// 解压包
	file, err := os.Open(packagePath)
	if err != nil {
		return fmt.Errorf("打开包文件失败: %v", err)
	}
	defer file.Close()

	gzr, err := gzip.NewReader(file)
	if err != nil {
		return fmt.Errorf("解压失败: %v", err)
	}
	defer gzr.Close()

	tr := tar.NewReader(gzr)

	// 遍历 tar 文件内容
	for {
		header, err := tr.Next()
		if err == io.EOF {
			break // 结束
		}
		if err != nil {
			return fmt.Errorf("读取 tar 文件失败: %v", err)
		}

		// 构建目标路径
		// 跳过顶层目录
		fileName := header.Name
		if strings.Contains(fileName, "/") {
			fileName = strings.SplitN(fileName, "/", 2)[1]
		}
		if fileName == "" {
			continue
		}

		target := filepath.Join(installPath, fileName)

		// 处理目录
		if header.Typeflag == tar.TypeDir {
			if _, err := os.Stat(target); os.IsNotExist(err) {
				if err := os.MkdirAll(target, 0755); err != nil {
					return fmt.Errorf("创建目录失败: %v", err)
				}
			}
			continue
		}

		// 处理文件
		if header.Typeflag == tar.TypeReg {
			// 创建父目录
			dir := filepath.Dir(target)
			if _, err := os.Stat(dir); os.IsNotExist(err) {
				if err := os.MkdirAll(dir, 0755); err != nil {
					return fmt.Errorf("创建目录失败: %v", err)
				}
			}

			// 创建文件
			file, err := os.Create(target)
			if err != nil {
				return fmt.Errorf("创建文件失败: %v", err)
			}

			// 设置文件权限
			if err := os.Chmod(target, os.FileMode(header.Mode)); err != nil {
				file.Close()
				return fmt.Errorf("设置文件权限失败: %v", err)
			}

			// 写入文件内容
			if _, err := io.Copy(file, tr); err != nil {
				file.Close()
				return fmt.Errorf("写入文件内容失败: %v", err)
			}

			file.Close()
		}
	}

	// 记录安装信息
	_, err = pm.db.Exec(`
		INSERT INTO installed_packages (name, version, path) VALUES (?, ?, ?)
	`, metadata.Name, metadata.Version, installPath)
	if err != nil {
		return fmt.Errorf("记录安装信息失败: %v", err)
	}

	return nil
}

// 检查包是否已安装
func (pm *PackageManager) IsPackageInstalled(packageName, version string) bool {
	var count int
	err := pm.db.QueryRow(`
		SELECT COUNT(*) FROM installed_packages WHERE name = ? AND version = ?
	`, packageName, version).Scan(&count)

	return err == nil && count > 0
}

// 卸载包
func (pm *PackageManager) UninstallPackage(packageName, version string) error {
	// 检查是否已安装
	if !pm.IsPackageInstalled(packageName, version) {
		return fmt.Errorf("%s@%s 未安装", packageName, version)
	}

	// 获取安装路径
	var installPath string
	err := pm.db.QueryRow(`
		SELECT path FROM installed_packages WHERE name = ? AND version = ?
	`, packageName, version).Scan(&installPath)

	if err != nil {
		return fmt.Errorf("查询安装路径失败: %v", err)
	}

	// 删除安装目录
	if err := os.RemoveAll(installPath); err != nil {
		return fmt.Errorf("删除安装目录失败: %v", err)
	}

	// 从数据库中删除记录
	_, err = pm.db.Exec(`
		DELETE FROM installed_packages WHERE name = ? AND version = ?
	`, packageName, version)

	if err != nil {
		return fmt.Errorf("删除安装记录失败: %v", err)
	}

	fmt.Printf("成功卸载 %s@%s\n", packageName, version)
	return nil
}

// 列出已安装的包
func (pm *PackageManager) ListInstalledPackages() ([]ResolvedDependency, error) {
	rows, err := pm.db.Query(`
		SELECT name, version, path FROM installed_packages ORDER BY name, version
	`)

	if err != nil {
		return nil, fmt.Errorf("查询已安装包失败: %v", err)
	}
	defer rows.Close()

	var packages []ResolvedDependency
	for rows.Next() {
		var dep ResolvedDependency
		if err := rows.Scan(&dep.Name, &dep.Version, &dep.Path); err != nil {
			return nil, fmt.Errorf("扫描行失败: %v", err)
		}
		packages = append(packages, dep)
	}

	if err := rows.Err(); err != nil {
		return nil, fmt.Errorf("遍历结果集失败: %v", err)
	}

	return packages, nil
}

// 关闭包管理器
func (pm *PackageManager) Close() error {
	return pm.db.Close()
}

// 主函数
func main() {
	// 配置文件路径
	configPath := filepath.Join(os.UserHomeDir(), ".gomod", "config.json")

	// 创建包管理器
	pm, err := NewPackageManager(configPath)
	if err != nil {
		log.Fatalf("初始化包管理器失败: %v", err)
	}
	defer pm.Close()

	// 创建命令行解析器
	installCmd := flag.NewFlagSet("install", flag.ExitOnError)
	installPkg := installCmd.String("pkg", "", "包名")
	installVer := installCmd.String("version", "", "版本 (可选)")

	uninstallCmd := flag.NewFlagSet("uninstall", flag.ExitOnError)
	uninstallPkg := uninstallCmd.String("pkg", "", "包名")
	uninstallVer := uninstallCmd.String("version", "", "版本 (可选)")

	listCmd := flag.NewFlagSet("list", flag.ExitOnError)

	searchCmd := flag.NewFlagSet("search", flag.ExitOnError)
	searchQuery := searchCmd.String("query", "", "搜索查询")

	// 解析命令行参数
	if len(os.Args) < 2 {
		fmt.Println("使用方法: gopm [命令] [参数]")
		fmt.Println("可用命令: install, uninstall, list, search")
		os.Exit(1)
	}

	switch os.Args[1] {
	case "install":
		installCmd.Parse(os.Args[2:])
		if *installPkg == "" {
			installCmd.Usage()
			os.Exit(1)
		}

		version := *installVer
		if version == "" {
			version = "*" // 最新版本
		}

		if err := pm.InstallPackage(*installPkg, version); err != nil {
			log.Fatalf("安装失败: %v", err)
		}

	case "uninstall":
		uninstallCmd.Parse(os.Args[2:])
		if *uninstallPkg == "" {
			uninstallCmd.Usage()
			os.Exit(1)
		}

		version := *uninstallVer
		if version == "" {
			// 获取已安装的最新版本
			packages, err := pm.ListInstalledPackages()
			if err != nil {
				log.Fatalf("获取已安装包失败: %v", err)
			}

			var latestVersion string
			for _, pkg := range packages {
				if pkg.Name == *uninstallPkg {
					if latestVersion == "" || semver.Compare(pkg.Version, latestVersion) > 0 {
						latestVersion = pkg.Version
					}
				}
			}

			if latestVersion == "" {
				log.Fatalf("%s 未安装", *uninstallPkg)
			}

			version = latestVersion
		}

		if err := pm.UninstallPackage(*uninstallPkg, version); err != nil {
			log.Fatalf("卸载失败: %v", err)
		}

	case "list":
		listCmd.Parse(os.Args[2:])

		packages, err := pm.ListInstalledPackages()
		if err != nil {
			log.Fatalf("列出包失败: %v", err)
		}

		if len(packages) == 0 {
			fmt.Println("没有安装任何包")
			return
		}

		fmt.Println("已安装的包:")
		for _, pkg := range packages {
			fmt.Printf("- %-20s %s\n", pkg.Name, pkg.Version)
		}

	case "search":
		searchCmd.Parse(os.Args[2:])
		if *searchQuery == "" {
			searchCmd.Usage()
			os.Exit(1)
		}

		// 实际实现中会调用索引搜索 API
		// 这里简化为示例输出
		fmt.Printf("搜索结果: %s\n", *searchQuery)
		fmt.Println("- package1 v1.0.0 - 这是一个示例包")
		fmt.Println("- package2 v2.1.3 - 另一个示例包")
		fmt.Println("- package3 v0.5.0 - 包含相关功能的包")

	default:
		fmt.Println("未知命令:", os.Args[1])
		fmt.Println("可用命令: install, uninstall, list, search")
		os.Exit(1)
	}
}
